<?php
namespace Hilaoyu\LaravelExtend\Supports;
use Barryvdh\Snappy\PdfWrapper;
use Hilaoyu\LaravelExtend\Services\Files\FileService;
use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\LaravelExtend\Traits\ModelCommonTrait;
use Hilaoyu\Utils\UtilFile;


class PDF
{
    protected $pdf;

    /**
     * @param $view
     * @param array $data
     * @param array $mergeData
     * @return static
     */
    static public function makeFromView($view, $data = array(), $mergeData = array()){
        $pdf = app('snappy.pdf.wrapper');
        $pdf->loadView($view, $data, $mergeData);
        return new static($pdf);
    }

    public function __construct(PdfWrapper $pdf)
    {
        $this->pdf = $pdf;
    }

    public function download($file_name=''){
        !$file_name && $file_name = uniqid('pdf').'.pdf';
        return $this->pdf->download($file_name);
    }

    /**
     * @param string $disk
     * @param null $path
     * @return FileService|null
     */

    public function saveToFs($disk='',$path=null){
        if(!$disk){
            $disk = FileService::tempDisk();
        }
        if(!$path){
            $path = FileService::generateHashPath(null,null,'pdf');
        }
        $Fs = new FileService($disk,$path);
        UtilFile::checkDir(UtilFile::dirname($Fs->path(true)));


        if($this->pdf->save($Fs->path(true),true)){
            return $Fs;
        }
        return null;
    }
}